/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */
import type { MaProTableColumns, MaProTableExpose } from "@mineadmin/pro-table";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import defaultAvatar from "@/assets/images/defaultAvatar.jpg";
import { ElTag, ElImage } from "element-plus";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import hasAuth from "@/utils/permission/hasAuth.ts";
import {
  deleteByIds,
  userList,
} from "$/attractions/commerce/api/commerceMerchant.ts";

export default function getTableColumns(
  dialog: UseDialogExpose,
  formRef: any,
  t: any
): MaProTableColumns[] {
  const msg = useMessage();

  const adminList = ref<any[]>([]);

  onMounted(async () => {
    const response = await userList({ page: 1, limit: 1000 });
    if (response.code === 200 && response.data && response.data.list) {
      adminList.value = response.data.list;
    }
  });

  return [
    {
      type: "selection",
      showOverflowTooltip: false,
      label: () => t("crud.selection"),
    },
    {
      label: "管理员",
      prop: "admin_id",
      cellRender: ({ row }) => {
        const admin = adminList.value.find(
          (admin) => admin.id === row.admin_id
        );
        return admin ? admin.username : `管理员${row.admin_id}`;
      },
    },
    { label: "商户名称", prop: "merchant_name" },
    {
      label: "商户类型",
      prop: "merchant_type",
      cellRender: ({ row }) => {
        const satatusMap = {
          1: { text: "个体户", type: "success" },
          2: { text: "企业", type: "warning" },
          3: { text: "虚拟商户", type: "info" },
          4: { text: "合作社", type: "danger" },
          5: { text: "政府单位", type: "info" },
        };
        const status = satatusMap[row.merchant_type] || {
          text: "未知",
          type: "info",
        };
        return h(ElTag, { type: status.type }, () => status.text);
      },
    },
    { label: "法人代表", prop: "legal_person" },
    { label: "法人联系方式", prop: "legal_person_phone" },
    {
      label: "法人身份证",
      prop: "legal_person_id_card",
      renderProps: { multiple: false },
    },
    { label: "商户联系人", prop: "contact_person" },
    { label: "商户联系电话", prop: "contact_phone" },
    { label: "联系邮箱", prop: "contact_email" },
    { label: "商店地址", prop: "address" },
    { label: "商户开门时间", prop: "open_time", mode: "date", showTime: true },
    { label: "商户关门时间", prop: "close_time", mode: "date", showTime: true },
    { label: "注册资本", prop: "registered_capital" },
    {
      label: "成立日期",
      prop: "established_date",
      mode: "date",
      showTime: false,
    },
    {
      label: "营业执照照片",
      prop: "business_license_url",
      cellRender: ({ row }) => {
        if (!row.business_license_url) {
          return h("span", { style: { color: "#999" } }, "暂无图片");
        }

        // 获取API基础URL
        const env = import.meta.env;
        const baseUrl =
          env.VITE_OPEN_PROXY === "true"
            ? env.VITE_PROXY_PREFIX
            : env.VITE_APP_API_BASEURL;
        const imageUrl = `${baseUrl}${row.business_license_url}`;

        return h(
          ElImage,
          {
            src: imageUrl,
            alt: "营业执照",
            style: {
              width: "60px",
              height: "40px",
              borderRadius: "4px",
              border: "1px solid #ddd",
            },
            fit: "cover",
            previewSrcList: [imageUrl],
            previewTeleported: true,
            onError: () => {
              // 图片加载失败时的处理可以通过 ElImage 的 error slot 处理
              console.warn("营业执照图片加载失败:", imageUrl);
            },
          },
          {
            error: () =>
              h(
                "div",
                {
                  style: {
                    width: "60px",
                    height: "40px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    backgroundColor: "#f5f5f5",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    fontSize: "12px",
                    color: "#999",
                  },
                },
                "加载失败"
              ),
          }
        );
      },
    },
    { label: "营业执照号", prop: "business_license" },
    { label: "税务登记号", prop: "tax_id", renderProps: { multiple: false } },
    { label: "开户银行", prop: "bank_name" },
    { label: "银行账号", prop: "bank_account" },
    {
      type: "operation",
      label: () => t("crud.operation"),
      fixed: "right",
      operationConfigure: {
        actions: [
          {
            name: "edit",
            icon: "material-symbols:person-edit",
            show: ({ row }) =>
              hasAuth("commerce_merchant:commerceMerchant:update"),
            text: () => t("crud.edit"),
            onClick: ({ row }) => {
              dialog.setTitle(t("crud.edit"));
              dialog.open({ formType: "edit", data: row });
            },
          },
          {
            name: "del",
            icon: "mdi:delete",
            text: () => t("crud.delete"),
            show: ({ row }) =>
              hasAuth("commerce_merchant:commerceMerchant:delete"),
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm(t("crud.delDataMessage")).then(async () => {
                const response = await deleteByIds([row.id]);
                if (response.code === ResultCode.SUCCESS) {
                  msg.success(t("crud.delSuccess"));
                  proxy.refresh();
                }
              });
            },
          },
        ],
      },
    },
  ];
}
